module.exports = {
  trigger: {
    // 自动维护 createTime 和 updateTime
    beforeCreate: async function({ addDataList }) {
      const now = Date.now();
      addDataList.forEach(item => {
        item.createTime = now;
        item.updateTime = now;
      });
    },
    beforeUpdate: async function({ updateData }) {
      updateData.updateTime = Date.now();
    },

    // 防止非法状态变更
    beforeUpdate: async function({ docId, updateData }) {
      const db = uniCloud.database();

      // 仅当 status 被修改时触发检查
      if (updateData.hasOwnProperty('status')) {
        // 获取当前记录的原始状态
        const { data: records } = await db.collection('ad')
          .doc(docId)
          .field('status')
          .get();

        if (!records || records.length === 0) {
          throw new Error('记录不存在');
        }

        const oldStatus = records[0].status;
        const newStatus = updateData.status;

        // 定义非法状态变更规则
        const invalidTransitions = {
          completed: ['pending', 'processing'],
          cancelled: ['pending', 'processing']
        };

        // 检查是否触发非法变更
        const isInvalid = (
          (invalidTransitions.completed.includes(newStatus) && oldStatus === 'completed') ||
          (invalidTransitions.cancelled.includes(newStatus) && oldStatus === 'cancelled')
        );

        if (isInvalid) {
          throw new Error(`状态已为 [${oldStatus}]，禁止修改为 [${newStatus}]`);
        }

        // 防御性校验：禁止从完成/取消状态修改为任何其他状态
        if (['completed', 'cancelled'].includes(oldStatus) && oldStatus !== newStatus) {
          throw new Error(`状态 [${oldStatus}] 不可修改`);
        }
      }
    }
  }
};